from django.db.models.signals import post_migrate
from django.dispatch import receiver
from django.contrib.auth import get_user_model
from django.db.utils import IntegrityError
from userManager.models import UserRole

@receiver(post_migrate)
def create_superuser(sender, **kwargs):
    User = get_user_model()
    try:
        # 检查用户是否已存在
        if not User.objects.filter(username='admin').exists():
            super_user = User.objects.create_superuser('admin', 'admin@example.com', '123456')
            user_role = UserRole(user=super_user)
            user_role.role = 'admin'
            user_role.jnumber = '1234567'
            user_role.img = 'avatar1.png'
            user_role.phone = '123'
            user_role.gender = '1'
            user_role.save()
            print("Superuser created.")

    except IntegrityError:
        pass  # 如果用户已存在，则忽略
